package com.hjb.service.impl.product;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.hjb.service.recharge.FYRechargeService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hjb.service.common.CommonKeyValueService;
import com.hjb.service.common.HolidayService;
import com.hjb.service.config.constant.Constants;
import com.hjb.service.domain.product.Product;
import com.hjb.service.domain.product.ProductExample;
import com.hjb.service.domain.product.SiteUserBuy;
import com.hjb.service.domain.recharge.SiteUserRecharge;
import com.hjb.service.domain.siteuser.SiteUser;
import com.hjb.service.domain.siteuser.SiteUserAccountLog;
import com.hjb.service.domain.siteuser.SiteUserAddRate;
import com.hjb.service.domain.siteuser.SiteUserExample;
import com.hjb.service.domain.siteuser.SiteUserExperience;
import com.hjb.service.domain.siteuser.SiteUserExperienceExample;
import com.hjb.service.domain.siteuser.SiteUserFixed;
import com.hjb.service.domain.siteuser.SiteUserLimit;
import com.hjb.service.domain.siteuseraccount.SiteUserAccount;
import com.hjb.service.domain.siteuseraccount.SiteUserAccountExample;
import com.hjb.service.domain.siteusercoupon.SiteUserCoupon;
import com.hjb.service.domain.siteusercoupon.SiteUserCouponExample;
import com.hjb.service.domain.siteuserenvelop.SiteUserEnvelop;
import com.hjb.service.domain.siteuserenvelop.SiteUserEnvelopExample;
import com.hjb.service.domain.withdraw.PayCashWithdraw;
import com.hjb.service.mapper.PayCashWithdrawMapper;
import com.hjb.service.mapper.ProductMapper;
import com.hjb.service.mapper.SiteUserAccountLogMapper;
import com.hjb.service.mapper.SiteUserAccountMapper;
import com.hjb.service.mapper.SiteUserAddRateMapper;
import com.hjb.service.mapper.SiteUserExperienceMapper;
import com.hjb.service.mapper.SiteUserFixedMapper;
import com.hjb.service.mapper.SiteUserLimitMapper;
import com.hjb.service.mapper.SiteUserMapper;
import com.hjb.service.mapper.SiteUserProfitMapper;
import com.hjb.service.product.ProductService;
import com.hjb.service.product.SiteUserBuyService;
import com.hjb.service.siteuseraccount.SiteUserBankcardService;
import com.hjb.service.user.SiteUserAccountService;
import com.hjb.service.user.SiteUserCouponService;
import com.hjb.service.user.SiteUserCurrentService;
import com.hjb.service.user.SiteUserEnvelopService;
import com.hjb.service.user.SiteUserFixedService;
import com.hjb.service.user.SiteUserService;
import com.hjb.service.utils.HJBUT;
import com.hjb.service.utils.MD5Utils;
import com.hjb.service.utils.MapUtil;
import com.hjb.service.utils.TradeDateUtil;

/**
 * 产品接口业务实现类
 * @author zhangxl
 * @date 2017-07-20
 * @version 1.0
 */
@Service
public class ProductServiceImpl implements ProductService {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private ProductService productService;
	@Autowired
	private SiteUserService siteUserService;
	@Autowired
	private HolidayService holidayService;
	@Autowired
	private SiteUserCurrentService siteUserCurrentService;
	@Autowired
	private SiteUserAccountService siteUserAccountService;
	@Autowired
	private SiteUserCouponService siteUserCouponService;
	@Autowired
	private SiteUserBuyService siteUserBuyService;
	@Autowired
	private SiteUserEnvelopService siteUserEnvelopService;
	@Autowired
	private FYRechargeService fyRechargeService;
	@Autowired
	private CommonKeyValueService commonKeyValueService;
	@Autowired
	private SiteUserAccountMapper siteUserAccountMapper;
	@Autowired
	private SiteUserAddRateMapper siteUserAddRateMapper;
	@Autowired
	private SiteUserProfitMapper siteUserProfitMapper;
	@Autowired
	private SiteUserLimitMapper siteUserLimitMapper;
	@Autowired
	private PayCashWithdrawMapper payCashWithdrawMapper;
	@Autowired
	private SiteUserExperienceMapper siteUserExperienceMapper;
	@Autowired
	private SiteUserFixedService siteUserFixedService;
	@Autowired
	private SiteUserFixedMapper siteUserFixedMapper;
	@Autowired
	private SiteUserBankcardService siteUserBankcardService;
	@Autowired
	private SiteUserAccountLogMapper siteUserAccountLogMapper;
	@Autowired
	private SiteUserMapper siteUserMapper;
	
	@Override
	public List<Map<String,Object>> getProductList(Map<String, Object> params) {
		List<Map<String,Object>> productList = productMapper.queryProductList(params);
		setProductMap(productList);
		return productList;
	}
	
	public void setProductMap(List<Map<String,Object>> productList){
		for(Map<String,Object> voMap :productList){
			String dateStr = "";
			String addRate = "";
			if(voMap.get("productTime") !=null){
				dateStr =voMap.get("productTime")+"天";
			}
			if(voMap.get("addRate") !=null){
				addRate =String.valueOf(voMap.get("addRate"));
			}
			if(voMap.get("productType") != null){
				int productType = Integer.parseInt(String.valueOf(voMap.get("productType")));
				if(productType == Constants.PRODUCT_TYPE_3){
					//是否在售,0:可购 1，不可够
					String sanpUp = "1";
					BigDecimal balance = new BigDecimal(String.valueOf(voMap.get("balance")));
					if(balance.compareTo(BigDecimal.ZERO) >0){
						sanpUp = "0";
					}
					voMap.put("sanpUp", sanpUp);
				}
				if(productType == Constants.PRODUCT_TYPE_1){
					BigDecimal productRate = new BigDecimal(String.valueOf(voMap.get("rate")));
					if(voMap.get("addRate") != null){
						productRate = productRate.add(new BigDecimal(String.valueOf(voMap.get("addRate"))));
					}
					String productRateStr = String.valueOf(productRate);

					//计算复合利率
					BigDecimal compounRate = HJBUT.getCompoundRate(Double.parseDouble(productRateStr));
					voMap.put("compounRate", compounRate);
					voMap.put("compounRateStr", String.valueOf(compounRate));
				}
			}
			
			voMap.put("productId",String.valueOf(voMap.get("productId")));
			voMap.put("interestType",String.valueOf(voMap.get("interestType")));
			voMap.put("dateStr",dateStr);
			voMap.put("rate",String.valueOf(voMap.get("rate")));
			voMap.put("addRate",addRate);
			voMap.put("minAmount",String.valueOf(voMap.get("minAmount")));
			voMap.put("minAmountStr",String.valueOf(voMap.get("minAmount")+"元起投"));
			voMap.put("maxAmount",String.valueOf(voMap.get("maxAmount")));
			voMap.put("stepAmount",String.valueOf(voMap.get("stepAmount")));
			voMap.put("isCoupon",String.valueOf(voMap.get("isCoupon")));
			voMap.put("isPacket",String.valueOf(voMap.get("isPacket")));
			voMap.put("stauts",String.valueOf(voMap.get("stauts")));
			voMap.put("interestTypeStr","T+"+voMap.get("stauts")+"起息");
			voMap.put("redeemTypeStr","T+"+voMap.get("stauts")+"赎回到账");
			
		}
	}

	@Override
	public int insertProudt(Product product) {
		return productMapper.insertSelective(product);
	}

	@Override
	public int updateProudt(Product product) {
		return productMapper.updateByPrimaryKey(product);
	}

	@Override
	public Map<String, Object> getProductInfo(Map<String, Object> params) {
		Map<String,Object> productMap = null;
		List<Map<String,Object>> productList = productMapper.queryProductList(params);
		setProductMap(productList);
		if(productList.size() >0){
			productMap = productList.get(0);
		}
		
		return productMap;
	}

	@Override
	@Transactional
	public Map<String, Object> buyCurrentProduct(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}

		String userIdStr = String.valueOf(siteUser.getUserId());
		String productId = request.getParameter("product_id");
		String bidAmountStr = request.getParameter("bid_amount");
		String couponId = request.getParameter("coupon_id");
		String sysOs = request.getParameter("os");
		String tradePwd = request.getParameter("trade_pwd");
		Integer userId = Integer.parseInt(userIdStr);
		
		//检查用户投资条件
		Map<String,Object> checkResMap = checkPurchaseCondition(userId,Constants.PRODUCT_TYPE_1,tradePwd);
		if(!MapUtil.INTF_SUC_CODE.equals(checkResMap.get("code"))){
			resMap.put("result_code", checkResMap.get("code"));
			resMap.put("result_info", checkResMap.get("msg"));
			return resMap;
		}
		
		//查询产品信息
		params.put("productId", productId);
		Map<String, Object> productMap = productService.getProductInfo(params);
		if(productMap == null){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "产品信息不存在!");
			return resMap;
		}
		
		if(productMap.get("productType") != null){
			int productType = Integer.parseInt(String.valueOf(productMap.get("productType")));
			if(productType != Constants.PRODUCT_TYPE_1){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "活期产品购买数据异常!");
				return resMap;
			}
		}
		
		//检查投资金额是否小于起投金额
		BigDecimal minAmount = BigDecimal.ZERO;
		BigDecimal maxAmount = BigDecimal.ZERO;
		BigDecimal bidAmount = new BigDecimal(bidAmountStr);
		if(productMap.get("minAmount") != null){
			minAmount =  new BigDecimal(String.valueOf(productMap.get("minAmount")));
		}
		if(productMap.get("maxAmount") != null){
			maxAmount =  new BigDecimal(String.valueOf(productMap.get("maxAmount")));
		}
		//设置起投金额
		if(minAmount != null && minAmount.compareTo(BigDecimal.ZERO) > 0){
			if(minAmount.compareTo(bidAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额不能小于起投金额!");
				return resMap;
			}
		}
		
		//设置限投金额
		if(maxAmount != null && maxAmount.compareTo(BigDecimal.ZERO) > 0){
			//持有活期金额
			BigDecimal totalCurrent = bidAmount;
			SiteUserAccountExample accountExample = new SiteUserAccountExample();
			accountExample.createCriteria().andUserIdEqualTo(userId);
			List<SiteUserAccount> accountList = siteUserAccountService.selectByExample(accountExample);
			if(accountList.size() > 0 ){
				SiteUserAccount siteUserAccount = accountList.get(0);
				if(siteUserAccount.getCurrentAccount() !=null){
					totalCurrent = totalCurrent.add(siteUserAccount.getCurrentAccount());
				}
			}
			
			//申购未确认活期金额
			params.put("userId", userId);
			params.put("status", Constants.COMMON_STATUS_0);
			params.put("productType", Constants.PRODUCT_TYPE_1);
			params.put("productId", productId);
			BigDecimal bidAmountTotal = siteUserBuyService.queryBidAmountTotal(params);
			if(bidAmountTotal != null){
				totalCurrent = totalCurrent.add(bidAmountTotal);
			}
			
			if(totalCurrent.compareTo(maxAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额超过上限!");
				return resMap;
			}
		}
		
		//查询加息券信息
		SiteUserCoupon userCoupon = null;
		if(StringUtils.isNotBlank(couponId)){
			SiteUserCouponExample userCouponExample = new SiteUserCouponExample();
			userCouponExample.createCriteria().andIdEqualTo(Long.parseLong(couponId)).andStatusEqualTo(Constants.COMMON_STATUS_0);
			List<SiteUserCoupon> userCouponList = siteUserCouponService.selectByExample(userCouponExample);
			if(userCouponList.size() >0){
				userCoupon = userCouponList.get(0);
				if(userCoupon.getMinInvestAmount() != null && userCoupon.getMinInvestAmount().compareTo(bidAmount) >0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "投资金额小于加息券起投金额！");
					return resMap;
				}
				if(userCoupon.getMaxInvestAmount() !=null && userCoupon.getMaxInvestAmount().compareTo(BigDecimal.ZERO) > 0
						&& bidAmount.compareTo(userCoupon.getMaxInvestAmount()) >0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "投资金额大于加息券限投金额！");
					return resMap;
				}
				
			}else{
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "加息券已使用或已失效！");
				return resMap;
			}
		}
		
		BigDecimal rate = new BigDecimal(String.valueOf(productMap.get("rate")));
		//产品加息
		if(StringUtils.isNotBlank(String.valueOf(productMap.get("addRate")))){
			BigDecimal addRate = new BigDecimal(String.valueOf(productMap.get("addRate")));
			rate = rate.add(addRate);
		}
		
		//计算预计计息日、利息到账日
		List<String> holidayList = holidayService.queryHolidayList();
		
		String nextDay = TradeDateUtil.getDayExceptWeekend(HJBUT.currentDate(1));
		nextDay = TradeDateUtil.getDayAfterHoliday(nextDay, holidayList);
				
		long timeMillis = System.currentTimeMillis();
		//保存订单
		SiteUserBuy siteUserBuy = new SiteUserBuy();
		siteUserBuy.setOrderNo(timeMillis+userIdStr);
		siteUserBuy.setUserId(userId);
		siteUserBuy.setAmount(bidAmount);
		siteUserBuy.setProductId(Integer.parseInt(productId));
		siteUserBuy.setPayType(Constants.PAY_TYPE_1);
		siteUserBuy.setApplyTime(new Date());
		siteUserBuy.setApplyDate(HJBUT.getCurrentDate());
		siteUserBuy.setStatus(Constants.COMMON_STATUS_0);
		siteUserBuy.setTerminalType(getTerminalType(sysOs));
		siteUserBuy.setRate(rate);
		siteUserBuy.setProductType(Constants.PRODUCT_TYPE_1);
		siteUserBuy.setIp(request.getRemoteAddr());
		siteUserBuy.setInterestDate(nextDay);
		siteUserBuy.setCashReturnDate(HJBUT.currentDate(nextDay, 1));
		if(StringUtils.isNotBlank(couponId) && userCoupon !=null){
			siteUserBuy.setCouponId(couponId);
			siteUserBuy.setAddRate(userCoupon.getAmount());
		}
		
		int res =siteUserBuyService.insertSiteUserBuy(siteUserBuy);
		if(res != 1){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "申购失败！");
			return resMap;
		}
		
		String info = "投资&"+productMap.get("productName");
		String bankMsg = siteUserBankcardService.queryBankInfobyUserId(siteUser.getUserId());
		String inMsg = "用户银行卡（"+bankMsg+"）";
		//记录日志
		SiteUserAccountLog userAccountLog = new SiteUserAccountLog();
		userAccountLog.setUserId(userId);
		userAccountLog.setAcctType(Constants.ACCOUNT_LOG_TYPE_1);
		userAccountLog.setCreateTime(new Date());
		userAccountLog.setInAccount(userId);
		userAccountLog.setOutAccount(userId);
		userAccountLog.setAmount(siteUserBuy.getAmount());
		userAccountLog.setStatus(Constants.COMMON_STATUS_3);
		userAccountLog.setOrderId(siteUserBuy.getOrderNo());
		userAccountLog.setCurrnetOrder("");
		userAccountLog.setFixedOrder("");
		userAccountLog.setInfo(info);
		userAccountLog.setInMsg("活期");
		userAccountLog.setOutMsg(inMsg);
		siteUserAccountLogMapper.insertSelective(userAccountLog);
		
		Map<String,Object> orderInfo = fyRechargeService.recharge(siteUserBuy);
		//银行卡充值
//		Map<String,Object> rechargeResMap = payService.recharge(siteUserBuy);
//		if(rechargeResMap == null){
//			log.info("充值失败：充值对象为null   user_id:"+userIdStr);
//			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//			resMap.put("result_info", "申购失败！");
//			return resMap;
//		}
//		if(!MapUtil.INTF_SUC_CODE.equals(rechargeResMap.get("result_code"))){
//			log.info("充值失败：order_no:"+siteUserBuy.getOrderNo()+"，充值结果："+rechargeResMap.get("result_info"));
//			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//			resMap.put("result_info", rechargeResMap.get("result_info"));
//			return resMap;
//		}
		
		//更新加息券状态
		if(StringUtils.isNotBlank(couponId) && userCoupon !=null){
			SiteUserCoupon updateCoupon = new SiteUserCoupon();
			updateCoupon.setId(userCoupon.getId());
			updateCoupon.setStatus(Constants.COMMON_STATUS_1);
			updateCoupon.setUseTime(new Date());
			siteUserCouponService.updateSiteUserCoupon(updateCoupon);
		}
		
		//查询用户信息
		SiteUser queryUser = new SiteUser();
		queryUser.setUserId(userId);
		queryUser = siteUserService.selectOneByExample(siteUser);
		
		//未绑卡
		if(queryUser.getIsBindCard() == 0){
			log.info("未绑卡进行申购操作，userId:"+userId);
			resMap.put("result_code",MapUtil.INTF_ERR_CODE_301);
			resMap.put("result_info", "未绑定银行卡！");
			return resMap;
		}
		
		/*Map<String,Object> userInfoMap = new HashMap<String, Object>();
		userInfoMap.put("userId", queryUser.getUserId());
		userInfoMap.put("orderNo", siteUserBuy.getOrderNo());
		userInfoMap.put("amount", siteUserBuy.getAmount());
		userInfoMap.put("bankCode", queryUser.getBankCode());
		userInfoMap.put("bankName", queryUser.getBankName());
		userInfoMap.put("bankPhone", queryUser.getBankPhone());
		userInfoMap.put("realName", queryUser.getRealName());
		userInfoMap.put("cardNumber", queryUser.getCardNumber());
		userInfoMap.put("cardType", "借记卡");
		if (siteUser.getBankCardNo() != null && !"".equals(siteUser.getBankCardNo())) {
			if (siteUser.getBankCardNo().length() > 8) {
				userInfoMap.put("bankCardNo", siteUser.getBankCardNo().substring(0, 4) + "****" + siteUser.getBankCardNo().substring(8));
			}else {
				userInfoMap.put("bankCardNo", siteUser.getBankCardNo());
			}
		}*/
		
		dataMap.put("bidMsg", "恭喜您成功申购活期"+bidAmountStr+"元");
		dataMap.put("bidDate", HJBUT.currentTime());
		dataMap.put("interestMsg", "预计"+nextDay+"计算份额");
		dataMap.put("incomeMsg", "预计"+HJBUT.currentDate(nextDay, 1)+"首笔收益到账");

		dataMap.putAll(orderInfo);
		resMap.put("data", dataMap);
		
		return resMap;
	}
	
	@Override
	@Transactional
	public Map<String, Object> buyRegularProduct(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		String userIdStr = String.valueOf(siteUser.getUserId());
		String productId = request.getParameter("product_id");
		String bidAmountStr = request.getParameter("bid_amount");
		String couponId = request.getParameter("coupon_id");
		String redPacketId = request.getParameter("red_id");
		String returnType = request.getParameter("return_type");
		String payType = request.getParameter("pay_type");
		String tradePwd = request.getParameter("trade_pwd");
		String sysOs = request.getParameter("os");
		
		Integer userId = Integer.parseInt(userIdStr);
		
		//检查用户投资条件
		Map<String,Object> checkResMap = checkPurchaseCondition(userId,Constants.PRODUCT_TYPE_2,tradePwd);
		if(!MapUtil.INTF_SUC_CODE.equals(checkResMap.get("code"))){
			resMap.put("result_code", checkResMap.get("code"));
			resMap.put("result_info", checkResMap.get("msg"));
			return resMap;
		}
		
		//查询产品信息
		params.put("productId", productId);
		Map<String, Object> productMap = productService.getProductInfo(params);
		if(productMap == null){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "产品信息不存在!");
			return resMap;
		}
		
		if(productMap.get("productType") != null){
			int productType = Integer.parseInt(String.valueOf(productMap.get("productType")));
			if(productType != Constants.PRODUCT_TYPE_2){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "定期产品购买数据异常!");
				return resMap;
			}
		}
		
		//期限
		int productTime = 0;
		if(productMap.get("productTime") != null){
			productTime = Integer.parseInt(String.valueOf(productMap.get("productTime")));
		}
		//产品名称
		String productName = "";
		if(productMap.get("productName") != null){
			productName = String .valueOf(productMap.get("productName"));
		}
		
		//检查投资金额是否小于起投金额
		BigDecimal minAmount = BigDecimal.ZERO;
		BigDecimal maxAmount = BigDecimal.ZERO;
		BigDecimal bidAmount = new BigDecimal(bidAmountStr);
		if(productMap.get("minAmount") != null){
			minAmount =  new BigDecimal(String.valueOf(productMap.get("minAmount")));
		}
		if(productMap.get("maxAmount") != null){
			maxAmount =  new BigDecimal(String.valueOf(productMap.get("maxAmount")));
		}
		
		//设置起投金额
		if(minAmount != null && minAmount.compareTo(BigDecimal.ZERO) > 0){
			if(minAmount.compareTo(bidAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额不能小于起投金额!");
				return resMap;
			}
		}
		
		//设置限投金额
		if(maxAmount != null && maxAmount.compareTo(BigDecimal.ZERO) > 0){
			
			//购买期金额
			params.put("userId", userId);
			params.put("status", Constants.COMMON_STATUS_0);
			params.put("productType", Constants.PRODUCT_TYPE_2);
			params.put("productId", productId);
			BigDecimal bidAmountTotal = siteUserBuyService.queryBidAmountTotal(params);
			if(bidAmountTotal == null){
				bidAmountTotal = BigDecimal.ZERO;
			}
			bidAmountTotal = bidAmount.add(bidAmountTotal);
			
			if(bidAmountTotal.compareTo(maxAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额超过上限!");
				return resMap;
			}
		}
		
		//查询加息券信息
		SiteUserCoupon userCoupon = null;
		if(StringUtils.isNotBlank(couponId)){
			SiteUserCouponExample userCouponExample = new SiteUserCouponExample();
			userCouponExample.createCriteria().andIdEqualTo(Long.parseLong(couponId)).andStatusEqualTo(Constants.COMMON_STATUS_0);
			List<SiteUserCoupon> userCouponList = siteUserCouponService.selectByExample(userCouponExample);
			if(userCouponList.size() >0){
				userCoupon = userCouponList.get(0);
				if(userCoupon.getMinInvestAmount() != null && userCoupon.getMinInvestAmount().compareTo(bidAmount) >0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "投资金额小于加息券起投金额！");
					return resMap;
				}
				if(userCoupon.getMaxInvestAmount() !=null && userCoupon.getMaxInvestAmount().compareTo(BigDecimal.ZERO) > 0
						&& bidAmount.compareTo(userCoupon.getMaxInvestAmount()) >0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "投资金额大于加息券限投金额！");
					return resMap;
				}
			}else{
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "加息券已使用或已失效！");
				return resMap;
			}
		}
		
		//查询红包信息
		SiteUserEnvelop userEnvelop = null;
		if(StringUtils.isNotBlank(redPacketId)){
			SiteUserEnvelopExample userEnvelopExample = new SiteUserEnvelopExample();
			userEnvelopExample.createCriteria().andIdEqualTo(Long.parseLong(redPacketId)).andStatusEqualTo(Constants.COMMON_STATUS_0);
			List<SiteUserEnvelop> userEnvelopList = siteUserEnvelopService.selectByExample(userEnvelopExample);
			if(userEnvelopList.size() > 0 ){
				userEnvelop = userEnvelopList.get(0);
				if(userEnvelop.getMinInvestAmount() != null && userEnvelop.getMinInvestAmount().compareTo(bidAmount) >0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "投资金额小于红包起投金额！");
					return resMap;
				}
			}else{
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "红包已使用或已失效！");
				return resMap;
			}
		}
		
		//支付方式,活期支付
		SiteUserAccount siteUserAccount = null;
		if(StringUtils.isNotBlank(payType) && Constants.PAY_TYPE_2.equals(payType)){
			//持有活期金额
			SiteUserAccountExample accountExample = new SiteUserAccountExample();
			accountExample.createCriteria().andUserIdEqualTo(userId);
			List<SiteUserAccount> accountList = siteUserAccountService.selectByExample(accountExample);
			if(accountList.size() > 0 ){
			    siteUserAccount = accountList.get(0);
				if(siteUserAccount.getCurrentAccount() !=null && siteUserAccount.getCurrentAccount().compareTo(bidAmount) < 0){
					resMap.put("result_code", MapUtil.INTF_ERR_CODE);
					resMap.put("result_info", "活期余额不足支付，请选择银行卡支付！");
					return resMap;
				}
			}
		}
		
		BigDecimal rate = new BigDecimal(String.valueOf(productMap.get("rate")));
		//产品加息
		if(StringUtils.isNotBlank(String.valueOf(productMap.get("addRate")))){
			BigDecimal addRate = new BigDecimal(String.valueOf(productMap.get("addRate")));
			rate = rate.add(addRate);
		}
		
		//计算预计计息日、利息到账日
		List<String> holidayList = holidayService.queryHolidayList();
		
		String nextDay = TradeDateUtil.getDayExceptWeekend(HJBUT.currentDate(1));
		nextDay = TradeDateUtil.getDayAfterHoliday(nextDay, holidayList);
		String cashReturnDate = HJBUT.currentDate(nextDay, productTime);
		long timeMillis = System.currentTimeMillis();
		//保存订单
		SiteUserBuy siteUserBuy = new SiteUserBuy();
		siteUserBuy.setOrderNo(timeMillis+userIdStr);
		siteUserBuy.setUserId(userId);
		siteUserBuy.setAmount(bidAmount);
		siteUserBuy.setProductId(Integer.parseInt(productId));
		siteUserBuy.setApplyTime(new Date());
		siteUserBuy.setApplyDate(HJBUT.getCurrentDate());
		siteUserBuy.setStatus(Constants.COMMON_STATUS_0);
		siteUserBuy.setTerminalType(getTerminalType(sysOs));
		siteUserBuy.setRate(rate);
		siteUserBuy.setProductType(Constants.PRODUCT_TYPE_2);
		siteUserBuy.setReturnType(returnType);
		siteUserBuy.setPayType(payType);
		siteUserBuy.setInterestDate(nextDay);
		siteUserBuy.setCashReturnDate(cashReturnDate);
		if(StringUtils.isNotBlank(couponId) && userCoupon !=null){
			siteUserBuy.setCouponId(couponId);
			siteUserBuy.setAddRate(userCoupon.getAmount());
		}
		if(StringUtils.isNotBlank(redPacketId) && userEnvelop != null){
			siteUserBuy.setRedPacketId(redPacketId);
			siteUserBuy.setCash(userEnvelop.getAmount());
			siteUserBuy.setTureAmount(bidAmount.subtract(userEnvelop.getAmount()));
		}
		
		int res =siteUserBuyService.insertSiteUserBuy(siteUserBuy);
		if(res != 1){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "购买失败！");
			return resMap;
		}
		
		//支付方式，银行卡支付
//		if(StringUtils.isNotBlank(payType) && Constants.PAY_TYPE_1.equals(payType)){
//			//银行卡充值
//			Map<String,Object> rechargeResMap = payService.recharge(siteUserBuy);
//			if(rechargeResMap == null){
//				log.info("充值失败：充值对象为null   user_id:"+userIdStr);
//				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//				resMap.put("result_info", "申购失败！");
//				return resMap;
//			}
//			if(!MapUtil.INTF_SUC_CODE.equals(rechargeResMap.get("result_code"))){
//				log.info("充值失败：order_no:"+siteUserBuy.getOrderNo()+"，充值结果："+rechargeResMap.get("result_info"));
//				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//				resMap.put("result_info", rechargeResMap.get("result_info"));
//				return resMap;
//			}
//		}
		
		//银行卡支付
		if(StringUtils.isNotBlank(payType) && Constants.PAY_TYPE_1.equals(payType)){
			//查询用户信息
			SiteUser queryUser = new SiteUser();
			queryUser.setUserId(userId);
			queryUser = siteUserService.selectOneByExample(siteUser);
			
			//未绑卡
			if(queryUser.getIsBindCard() == 0){
				log.info("未绑卡进行申购操作，userId:"+userId);
				resMap.put("result_code",MapUtil.INTF_ERR_CODE_301);
				resMap.put("result_info", "未绑定银行卡！");
				return resMap;
			}
			/*Map<String,Object> userInfoMap = new HashMap<String, Object>();
			
			userInfoMap.put("userId", queryUser.getUserId());
			userInfoMap.put("orderNo", siteUserBuy.getOrderNo());
			userInfoMap.put("amount", siteUserBuy.getAmount());
			userInfoMap.put("bankCode", queryUser.getBankCode());
			userInfoMap.put("bankName", queryUser.getBankName());
			userInfoMap.put("bankPhone", queryUser.getBankPhone());
			userInfoMap.put("realName", queryUser.getRealName());
			userInfoMap.put("cardNumber", queryUser.getCardNumber());
			userInfoMap.put("cardType", "借记卡");
			if (siteUser.getBankCardNo() != null && !"".equals(siteUser.getBankCardNo())) {
				if (siteUser.getBankCardNo().length() > 8) {
					userInfoMap.put("bankCardNo", siteUser.getBankCardNo().substring(0, 4) + "****" + siteUser.getBankCardNo().substring(8));
				}else {
					userInfoMap.put("bankCardNo", siteUser.getBankCardNo());
				}
			}*/
			Map<String,Object> orderInfo = fyRechargeService.recharge(siteUserBuy);
			dataMap.putAll(orderInfo);
			
			String info = "投资&"+productMap.get("productName");
			String bankMsg = siteUserBankcardService.queryBankInfobyUserId(siteUser.getUserId());
			String inMsg = "用户银行卡（"+bankMsg+"）";
			//记录日志
			SiteUserAccountLog userAccountLog = new SiteUserAccountLog();
			userAccountLog.setUserId(userId);
			userAccountLog.setAcctType(Constants.ACCOUNT_LOG_TYPE_1);
			userAccountLog.setCreateTime(new Date());
			userAccountLog.setInAccount(userId);
			userAccountLog.setOutAccount(userId);
			userAccountLog.setAmount(siteUserBuy.getAmount());
			userAccountLog.setStatus(Constants.COMMON_STATUS_3);
			userAccountLog.setOrderId(siteUserBuy.getOrderNo());
			userAccountLog.setCurrnetOrder("");
			userAccountLog.setFixedOrder("");
			userAccountLog.setInfo(info);
			userAccountLog.setInMsg("定期");
			userAccountLog.setOutMsg(inMsg);
			siteUserAccountLogMapper.insertSelective(userAccountLog);
		}
		
		//支付方式,活期支付
		if(StringUtils.isNotBlank(payType) && Constants.PAY_TYPE_2.equals(payType)){
			String logDesc = "活期投资"+productMap.get("productName");
			int updateCurrentRes = siteUserAccountService.updateCurrentAccount(userId, bidAmount, Constants.ACCOUNT_LOG_TYPE_4,
					userId, userId,siteUserBuy.getOrderNo(), "", "", logDesc,"定期","活期");
			if(updateCurrentRes != 1){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "购买失败！");
				return resMap;
			}
			SiteUserRecharge userRecharge = new SiteUserRecharge();
			userRecharge.setUserId(userId);
			userRecharge.setOrderId(siteUserBuy.getOrderNo());
			userRecharge.setStatus(Constants.COMMON_STATUS_2);
			userRecharge.setRetMsgConf("活期持有余额支付成功！");
			userRecharge.setReplyTime(new Date());
			//支付成功，处理订单
			siteUserBuyService.rechargeNotify(userRecharge);
		}
		
		//更新加息券状态
		if(StringUtils.isNotBlank(couponId) && userCoupon !=null){
			SiteUserCoupon updateCoupon = new SiteUserCoupon();
			updateCoupon.setId(userCoupon.getId());
			updateCoupon.setStatus(Constants.COMMON_STATUS_1);
			updateCoupon.setUseTime(new Date());
			siteUserCouponService.updateSiteUserCoupon(updateCoupon);
		}
		
		//更新红包状态
		if(StringUtils.isNotBlank(redPacketId) && userEnvelop !=null){
			SiteUserEnvelop updateEnvelop = new SiteUserEnvelop();
			updateEnvelop.setId(userEnvelop.getId());
			updateEnvelop.setStatus(Constants.COMMON_STATUS_1);
			updateEnvelop.setUseTime(new Date());
			siteUserEnvelopService.updateSiteUserEnvelop(updateEnvelop);
		}
		
		//总计收益率
		BigDecimal totalRate = rate;
		if(siteUserBuy.getAddRate() != null){
			totalRate = totalRate.add(siteUserBuy.getAddRate());
		}
		//计算收益
		BigDecimal returnAmount = BigDecimal.ZERO;
		int totalDays = HJBUT.daysBetween(nextDay, cashReturnDate);
		returnAmount = HJBUT.getInterest(bidAmount, totalRate, totalDays);
		returnAmount = returnAmount.add(bidAmount);
		
		dataMap.put("bidMsg", "恭喜您成功购买"+productName+bidAmountStr+"元");
		dataMap.put("bidDate", HJBUT.currentTime());
		dataMap.put("interestMsg", "预计"+nextDay+"开始计息");
		dataMap.put("incomeMsg", "预计"+cashReturnDate+"收益到账，预计收益"+returnAmount+"元");
		
		resMap.put("data", dataMap);
		
		return resMap;
	}
	
	/**
	 * 申购前检查用户是否可以申购
	 * @param userId
	 * @return
	 */
	public Map<String,Object> checkPurchaseCondition(Integer userId,int productType,String tradePwd){
		Map<String,Object> resMap = new HashMap<String, Object>();
		resMap.put("code", "200");
		resMap.put("msg", "");
		SiteUserExample userExample = new SiteUserExample();
		userExample.createCriteria().andUserIdEqualTo(userId);
		List<SiteUser> userList = siteUserService.selectByExample(userExample);
		if(userList.size() ==0 ){
			log.info("未查询到用户信息！userId:"+userId);
			resMap.put("code", MapUtil.INTF_ERR_CODE_300);
			resMap.put("msg", "未查询到用户信息！");
			return resMap;
		}
		
		SiteUser user = userList.get(0);
		if(user.getIsBindCard() ==0){
			log.info("未绑卡进行申购操作，userId:"+userId);
			resMap.put("code", MapUtil.INTF_ERR_CODE_301);
			resMap.put("msg", "未绑定银行卡！");
			return resMap;
		}
		//定期标检查交易密码
//		if(productType == Constants.PRODUCT_TYPE_2){
			if(StringUtils.isBlank(user.getTradePassword())){
				log.info("未设置交易密码进行申购操作，userId:"+userId);
				resMap.put("code", MapUtil.INTF_ERR_CODE_417);
				resMap.put("msg", "未设置交易密码！");
				return resMap;
			}
			if(StringUtils.isBlank(tradePwd)){
				log.info("交易密码参数为空  进行申购操作，userId:"+userId);
				resMap.put("code", MapUtil.INTF_ERR_CODE_418);
				resMap.put("msg", "交易密码错误！");
				return resMap;
			}
			String tradePwdNew = MD5Utils.encrypt(tradePwd);
			if(!tradePwdNew.equals(user.getTradePassword())){
				log.info("交易密码错误  进行申购操作，userId:"+userId);
				resMap.put("code", MapUtil.INTF_ERR_CODE_418);
				resMap.put("msg", "交易密码错误！");
				return resMap;
			}
//		}
		
		return resMap;
	}

	/**
	 * 获取购买渠道
	 * @param sysOs
	 * @return
	 */
	public int getTerminalType(String sysOs){
		int terminalType = Constants.TERMINAL_TYPE_1;
		if(StringUtils.isNotBlank(sysOs)){
			if(Constants.TERMINAL_TYPE_IOS.equals(sysOs)){
				terminalType = Constants.TERMINAL_TYPE_2;
			}else if(Constants.TERMINAL_TYPE_ANDROID.equals(sysOs)){
				terminalType = Constants.TERMINAL_TYPE_3;
			}else if(Constants.TERMINAL_TYPE_H5.equals(sysOs)){
				terminalType = Constants.TERMINAL_TYPE_4;
			}else if(Constants.TERMINAL_TYPE_WECHAT.equals(sysOs)){
				terminalType = Constants.TERMINAL_TYPE_5;
			}
		}
		return terminalType;
	}

	@Override
	public Map<String, Object> myCurrentAccount(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		//检查是否风险测评
		String riskEvaluation = "去测评";
		if (siteUser != null) {
			SiteUser querySiteUser = new SiteUser();
			querySiteUser.setUserId(siteUser.getUserId());
			siteUser = siteUserService.selectOneByExample(querySiteUser);
//			if(siteUser.getRiskLevel() !=null){
//				riskEvaluation = "";
//			}
		}
		
		//查询产品信息
		params.put("type", "0");
		Map<String, Object> productInfoMap = getProductInfo(params);
		if(productInfoMap == null){
			log.info("未查询到活期理财数据");
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到活期数据");
			return resMap;
		}
		
		//查询账户持有活期
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		//活期持总额 = 活期持有 + 购买未转入 
		BigDecimal totalCurrentAccount = BigDecimal.ZERO;
		if(siteUserAccount.getCurrentAccount() != null){
			totalCurrentAccount = siteUserAccount.getCurrentAccount();
		}
		BigDecimal productRate = new BigDecimal(String.valueOf(productInfoMap.get("rate")));
		String addRateStr = String.valueOf(productInfoMap.get("addRate"));
		if(StringUtils.isNotBlank(addRateStr)){
			productRate = productRate.add(new BigDecimal(addRateStr));
		}
		String productRateStr = String.valueOf(productRate);
		
		//今日万元收益
		double thousandProfit = HJBUT.getThousandProfit(Double.parseDouble(productRateStr));
				
		//计算复合利率
		BigDecimal compounRate = HJBUT.getCompoundRate(Double.parseDouble(productRateStr));
		
 		String compounRateStr=compounRate+"%";
 		productRateStr +="%";
 				
		//购买未转入金额
		BigDecimal totalCurrent = siteUserCurrentService.queryTotalCurrentByUserId(String.valueOf(siteUser.getUserId()));
		if(totalCurrent !=null){
			totalCurrentAccount = totalCurrentAccount.add(totalCurrent);
		}
		
		//加息券加息
		BigDecimal addRate = null;
		//查询用户加息
		SiteUserAddRate userAddRate = new SiteUserAddRate();
		userAddRate.setUserId(siteUser.getUserId());
		userAddRate.setStatus(Constants.COMMON_STATUS_0);
		userAddRate = siteUserAddRateMapper.selectOne(userAddRate);
		if(userAddRate != null){
			addRate = userAddRate.getAddRate();
			compounRateStr +="+"+addRate+"%";
			productRateStr +="+"+addRate+"%";
		}
		
		
		//查询昨日收益
		params.put("userId", siteUser.getUserId());
		params.put("returnDate", HJBUT.currentDate());
		BigDecimal profit = siteUserProfitMapper.queryProfitAmount(params);
		if(profit == null){
			profit = BigDecimal.ZERO;
		}
		
		//7日收益
		int dayTotal = HJBUT.daysBetween(HJBUT.currentDate(-7),HJBUT.currentDate());
		String[] logindates = new String[dayTotal] ;//时间
	    String[] arr = new String[dayTotal];
	    String[] loginnums = new String[dayTotal];//
	    //当前日期-7
	    String firstDate = HJBUT.currentDate(-dayTotal);
		for(int i=1;i<=dayTotal;i++){
			String date = HJBUT.currentDate(firstDate, i);
			params.put("returnDate", date);
			BigDecimal profitAmount = siteUserProfitMapper.queryProfitAmount(params);
			if(profitAmount == null){
				profitAmount = BigDecimal.ZERO;
			}
			String dateStr = date.substring(5,7)+"."+date.substring(8,10);
			//查询登录次数
			logindates[i-1] = dateStr;
			loginnums[i-1] = String.valueOf(profitAmount.setScale(2,BigDecimal.ROUND_DOWN));
			arr[i-1] =String.valueOf(profitAmount.setScale(2,BigDecimal.ROUND_DOWN));
		}
		
		//取出Y轴最大、最小数 
		Arrays.sort(arr);
		String minAmount = arr[0];
		String maxAmount = arr[dayTotal-1];
		
		dataMap.put("riskEvaluation", riskEvaluation);
		dataMap.put("thousandProfit", thousandProfit);
		dataMap.put("minAmount", minAmount);
		dataMap.put("maxAmount", maxAmount);
		dataMap.put("amounts", loginnums);
		dataMap.put("dates", logindates);
		dataMap.put("compounRate", compounRateStr);
		dataMap.put("productRate", productRateStr);
		dataMap.put("profit", "¥"+profit.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("totalProfit", "¥"+String.valueOf(siteUserAccount.getTotalCurrentIncome().setScale(2, BigDecimal.ROUND_DOWN)));
		dataMap.put("totalCurrent", "¥"+String.valueOf(totalCurrentAccount.setScale(2, BigDecimal.ROUND_DOWN)));
		dataMap.put("product", productInfoMap);
		
		resMap.put("data",dataMap);
		return resMap;
	}
	
	@Override
	@Transactional
	public Map<String, Object> currentRedeem(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		
		String sysOs = request.getParameter("os");
		String tradePwd = request.getParameter("trade_pwd");
		//赎回金额
		String redeemAmountStr = request.getParameter("amount");
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		if(StringUtils.isBlank(redeemAmountStr)){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "参数异常");
			return resMap;
		}
		
		//检查用户投资条件
		Map<String,Object> checkResMap = checkPurchaseCondition(siteUser.getUserId(),Constants.PRODUCT_TYPE_1,tradePwd);
		if(!MapUtil.INTF_SUC_CODE.equals(checkResMap.get("code"))){
			resMap.put("result_code", checkResMap.get("code"));
			resMap.put("result_info", checkResMap.get("msg"));
			return resMap;
		}
		
		//设置最小提现金额
		BigDecimal minRedeemAmount = new BigDecimal(100);
		//赎回金额
		BigDecimal redeemAmount = new BigDecimal(redeemAmountStr);
		if(minRedeemAmount.compareTo(redeemAmount) >0){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "赎回金额不能低于最小赎回金额");
			return resMap;
		}
		
		//查询账户持有活期
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		
		//活期可赎回金额
		BigDecimal currentAccount = siteUserAccount.getCurrentAccount();
		if(currentAccount == null ){
			currentAccount = BigDecimal.ZERO;
		}
		
		if(redeemAmount.compareTo(currentAccount)>0){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "赎回金额不高于活期持有金额");
			return resMap;
		}
		
		//查询产品详情
		params.put("type", "0");
		Map<String, Object> productInfoMap = getProductInfo(params);
		if(productInfoMap == null){
			log.info("未查询到活期理财数据");  
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到活期数据");
			return resMap;
		}
		
		String productId = String.valueOf(productInfoMap.get("productId"));
		
		SiteUserLimit userLimit = new SiteUserLimit();
		userLimit.setUserId(siteUser.getUserId());
		userLimit = siteUserLimitMapper.selectOne(userLimit);
		
		if(userLimit == null){
			
		}
		
		//限额检查,单笔限额
		if(redeemAmount.compareTo(userLimit.getSingleLimit()) >0){
			log.info("单笔转出金额不得超过"+userLimit.getSingleLimit()+"元！");  
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "单笔转出金额不得超过"+userLimit.getSingleLimit()+"元！");
			return resMap;
		}
		
		//限额检查,单日限额
//		params = new HashMap<String, Object>();
//		params.put("type", 0);
//		params.put("startDate", HJBUT.getCurrentDate());
//		BigDecimal dayAmountLimit = payCashWithdrawMapper.queryWithdrawAnoumtByDate(params);
//		if(dayAmountLimit == null){
//			dayAmountLimit = BigDecimal.ZERO;
//		}
//		dayAmountLimit = dayAmountLimit.add(redeemAmount);
//		if(dayAmountLimit.compareTo(userLimit.getDayLimit()) >0){
//			log.info("单日转出金额不得超过"+userLimit.getDayLimit()+"元！");  
//			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//			resMap.put("result_info", "单日转出金额不得超过"+userLimit.getDayLimit()+"元！");
//			return resMap;
//		}
		if(redeemAmount.compareTo(userLimit.getDayLimit()) >0){
			log.info("单日转出金额不得超过"+userLimit.getDayLimit()+"元！");  
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "单日转出金额不得超过"+userLimit.getDayLimit()+"元！");
			return resMap;
		}
		
//		//限额检查,月限额
//		params.put("type", 1);
//		params.put("startDate", HJBUT.getFirstDayOfMonth());
//		params.put("endDate", HJBUT.getLastDayOfMonth());
//		BigDecimal monthAmountLimit = payCashWithdrawMapper.queryWithdrawAnoumtByDate(params);
//		
//		if(monthAmountLimit == null){
//			monthAmountLimit = BigDecimal.ZERO;
//		}
//		monthAmountLimit = monthAmountLimit.add(redeemAmount);
//		if(monthAmountLimit.compareTo(userLimit.getMonthLimit()) >0){
//			log.info("单月转出金额不得超过"+userLimit.getMonthLimit()+"元！");  
//			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
//			resMap.put("result_info", "单月转出金额不得超过"+userLimit.getMonthLimit()+"元！");
//			return resMap;
//		}
		if(redeemAmount.compareTo(userLimit.getMonthLimit()) >0){
			log.info("单月转出金额不得超过"+userLimit.getMonthLimit()+"元！");  
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "单月转出金额不得超过"+userLimit.getMonthLimit()+"元！");
			return resMap;
		}
		
		long timeMillis = System.currentTimeMillis();
		String orderNo = String.valueOf(timeMillis)+siteUser.getUserId();
		String bankMsg = siteUserBankcardService.queryBankInfobyUserId(siteUser.getUserId());
		String inMsg = "用户银行卡（"+bankMsg+"）";
		
		//用户持有金额减赎回金额，冻结金额增加 
		int updateCurrentRes = siteUserAccountService.updateCurrentAccount(siteUser.getUserId(), redeemAmount, Constants.ACCOUNT_LOG_TYPE_3, 
				siteUser.getUserId(), siteUser.getUserId(),orderNo, "", "", "活期赎回",inMsg,"活期");
		if(updateCurrentRes != 1){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "赎回申请失败！");
			return resMap;
		}
		siteUserAccountService.updateFrozenAccount(siteUser.getUserId(), redeemAmount.negate(), Constants.ACCOUNT_LOG_TYPE_3, null, null,
				orderNo, "", "", "活期赎回冻结金额增加");
		
		
		//扣手续费
		BigDecimal userFee = BigDecimal.ZERO;
		if(userLimit.getFreeNum() <1){
			userFee = new BigDecimal(2);
		}
		
		BigDecimal toAmount = redeemAmount.subtract(userFee);
		
		//计算预计计息日、利息到账日
		List<String> holidayList = holidayService.queryHolidayList();
		
		String nextDay = TradeDateUtil.getDayExceptWeekend(HJBUT.currentDate(1));
		nextDay = TradeDateUtil.getDayAfterHoliday(nextDay, holidayList);
		PayCashWithdraw payWithdram = new PayCashWithdraw();
		payWithdram.setOrderId(orderNo);
		payWithdram.setTerminalType(getTerminalType(sysOs));
		payWithdram.setAmount(toAmount);
		payWithdram.setUserFee(userFee);
		payWithdram.setUserId(siteUser.getUserId());
		payWithdram.setStatus(Constants.COMMON_STATUS_0);
		payWithdram.setSettleDate(HJBUT.getCurrentDate(nextDay,0));
		payWithdram.setProductId(Integer.parseInt(productId));
		payWithdram.setApplyDate(HJBUT.getCurrentDate());
		payWithdram.setApplyTime(new Date());
		payWithdram.setCheckStatus(Constants.COMMON_STATUS_0);
		payWithdram.setSettleTime(null);
		payCashWithdrawMapper.insertSelective(payWithdram);
		
		//更新限额信息
		int freeNum = userLimit.getFreeNum()-1;
		if(freeNum <0){
			freeNum = 0;
		}
		//日限额
		BigDecimal dayAmountLimit = userLimit.getDayLimit().subtract(redeemAmount);
		if(dayAmountLimit.compareTo(BigDecimal.ZERO) < 0){
			dayAmountLimit = BigDecimal.ZERO;
		}
		BigDecimal monthAmountLimit = userLimit.getMonthLimit().subtract(redeemAmount);
		if(monthAmountLimit.compareTo(BigDecimal.ZERO) < 0){
			monthAmountLimit = BigDecimal.ZERO;
		}
		
		SiteUserLimit updateUserLimit = new SiteUserLimit();
		updateUserLimit.setId(userLimit.getId());
		updateUserLimit.setUserId(siteUser.getUserId());
		updateUserLimit.setFreeNum(freeNum);
		updateUserLimit.setDayLimit(dayAmountLimit);
		updateUserLimit.setMonthLimit(monthAmountLimit);
		updateUserLimit.setUpdateTime(new Date());
		siteUserLimitMapper.updateByPrimaryKeySelective(updateUserLimit);
		
		String msg = "恭喜您成功申请赎回活期"+redeemAmount+"元，其中提现手续费"+userFee+"元（银行收取），应到账金额:"+toAmount+"元";
		dataMap.put("msgTop", msg);
		dataMap.put("toAmount", toAmount);
		dataMap.put("applyTime", HJBUT.currentTime());
		dataMap.put("msg", "预计"+nextDay+"到银行卡");
		resMap.put("data", dataMap);
		return resMap;
	}

	@Override
	public Map<String, Object> currentRedeemInfo(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		//查询产品信息
		params.put("type", "0");
		Map<String, Object> productInfoMap = getProductInfo(params);
		if(productInfoMap == null){
			log.info("未查询到活期理财数据");  
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到活期数据");
			return resMap;
		}
		params.put("type", Constants.PRODUCT_TYPE_1);
		List<Map<String, Object>> productList = productService.getProductList(params);
		
		//查询账户持有活期
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		
		//活期可赎回金额
		BigDecimal currentAccount = siteUserAccount.getCurrentAccount();
		if(currentAccount == null ){
			currentAccount = BigDecimal.ZERO;
		}
		
		//购买未转入金额
		BigDecimal totalCurrent = siteUserCurrentService.queryTotalCurrentByUserId(String.valueOf(siteUser.getUserId()));
		if(totalCurrent ==null){
			totalCurrent = BigDecimal.ZERO;
		}
		totalCurrent = currentAccount.add(totalCurrent);
		
		BigDecimal singleLimit = BigDecimal.ZERO;
		BigDecimal dayLimit = BigDecimal.ZERO;
		BigDecimal monthLimit = BigDecimal.ZERO;
		int feeNum = 0;

		//查询限额信息
		SiteUserLimit userLimit = new SiteUserLimit();
		userLimit.setUserId(siteUser.getUserId());
		userLimit = siteUserLimitMapper.selectOne(userLimit);
		if(userLimit !=null ){
			singleLimit = userLimit.getSingleLimit();
			dayLimit = userLimit.getDayLimit();
			monthLimit = userLimit.getMonthLimit();
			feeNum = userLimit.getFreeNum();
		}
		
		dataMap.put("bigLimit",1000000);
		dataMap.put("singleLimit",singleLimit);
		dataMap.put("dayLimit", dayLimit);
		dataMap.put("monthLimit", monthLimit);
		dataMap.put("feeNum", feeNum);
		
		dataMap.put("totalCurrent", totalCurrent.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("currentAccount", currentAccount.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("product", productInfoMap);
		dataMap.put("productList", productList);
		
		resMap.put("data", dataMap);
		
		return resMap;
	}

	@Override
	@Transactional
	public Map<String, Object> buyExperienceProduct(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		//参数
		String productId = request.getParameter("product_id");
		String bidAmountStr = request.getParameter("bid_amount");
		String sysOs = request.getParameter("os");
		
		if(StringUtils.isBlank(productId) || StringUtils.isBlank(bidAmountStr) || StringUtils.isBlank(sysOs)){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "参数异常");	
			return resMap;
		}
		BigDecimal bidAmount = new BigDecimal(bidAmountStr);
		
		//查询产品详情
		params.put("productId", productId);
		Map<String, Object> productMap = productService.getProductInfo(params);
		if(productMap == null){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "数据异常！");	
			return resMap;
		}
		
		if(productMap.get("productType") != null){
			int productType = Integer.parseInt(String.valueOf(productMap.get("productType")));
			if(productType != Constants.PRODUCT_TYPE_3){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "体验产品购买数据异常!");
				return resMap;
			}
		}
		
		//期限
		int productTime = 0;
		if(productMap.get("productTime") != null){
			productTime = Integer.parseInt(String.valueOf(productMap.get("productTime")));
		}
		//利率
		BigDecimal rate = BigDecimal.ZERO;
		if(productMap.get("rate") !=null){
			rate = new BigDecimal(String.valueOf(productMap.get("rate")));
		}
		
		//查询账户信息
		BigDecimal experienceAccount = BigDecimal.ZERO;
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		if(siteUserAccount.getExperienceAccount() != null){
			experienceAccount = siteUserAccount.getExperienceAccount();
		}
		
		//检查投资金额是否小于起投金额
		BigDecimal minAmount = BigDecimal.ZERO;
		BigDecimal maxAmount = BigDecimal.ZERO;
		BigDecimal productBalance = BigDecimal.ZERO;
		if(productMap.get("minAmount") != null){
			minAmount =  new BigDecimal(String.valueOf(productMap.get("minAmount")));
		}
		if(productMap.get("maxAmount") != null){
			maxAmount =  new BigDecimal(String.valueOf(productMap.get("maxAmount")));
		}
		if(productMap.get("balance") != null){
			productBalance =  new BigDecimal(String.valueOf(productMap.get("balance")));
		}
		//设置起投金额
		if(minAmount != null && minAmount.compareTo(BigDecimal.ZERO) > 0){
			if(minAmount.compareTo(bidAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额不能小于起投金额!");
				return resMap;
			}
		}
		
		//设置限投金额
		if(maxAmount != null && maxAmount.compareTo(BigDecimal.ZERO) > 0){
			//持有体验金金额
			BigDecimal totalCurrent = bidAmount;
			params = new HashMap<String, Object>();
			params.put("userId", siteUser.getUserId());
			params.put("productId", productId);
			BigDecimal bidTotalAmount = siteUserExperienceMapper.queryExperienceBidAmount(params);
			if(bidTotalAmount != null ){
				totalCurrent = totalCurrent.add(bidTotalAmount);
			}
			
			if(totalCurrent.compareTo(maxAmount) >0){
				resMap.put("result_code", MapUtil.INTF_ERR_CODE);
				resMap.put("result_info", "投资金额超过上限!");
				return resMap;
			}
		}
		
		//检查体验金投标金额
		if(productBalance.compareTo(BigDecimal.ZERO) <= 0){
			log.info("体检金投资，体验金金额不足 user_id:"+siteUser.getUserId()+",投标金额："+bidAmount+",体验金金额："+experienceAccount);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "体验标可购余额不足");
			return resMap;
		}
		
		if(bidAmount.compareTo(productBalance) >0){
			log.info("体检金投资，体验金金额不足 user_id:"+siteUser.getUserId()+",投标金额："+bidAmount+",体验金金额："+experienceAccount);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "体验标可购余额不足");
			return resMap;
		}	
		
		//检查体验金投标金额
		if(bidAmount.compareTo(experienceAccount) >0){
			log.info("体检金投资，体验金金额不足 user_id:"+siteUser.getUserId()+",投标金额："+bidAmount+",体验金金额："+experienceAccount);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "体验金余额不足");
			return resMap;
		}
		
		//更新产品可购金额
		params = new HashMap<String, Object>();
		params.put("amount", bidAmount);
		params.put("productId", productId);
		int updataRes = productMapper.updateProductBanlance(params);
		if(updataRes != 1){
			log.info("体验标购买失败，可购金额不足,user_id:"+siteUser.getUserId()+",购买金额:"+bidAmount);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "购买失败！");
			return resMap;
		}
		
		//计算预计计息日、利息到账日
		List<String> holidayList = holidayService.queryHolidayList();
		
		String nextDay = TradeDateUtil.getDayExceptWeekend(HJBUT.currentDate(1));
		nextDay = TradeDateUtil.getDayAfterHoliday(nextDay, holidayList);
				
		long timeMillis = System.currentTimeMillis();
		String orderNo = timeMillis+String.valueOf(siteUser.getUserId());
		//保存订单
		SiteUserBuy siteUserBuy = new SiteUserBuy();
		siteUserBuy.setOrderNo(orderNo);
		siteUserBuy.setUserId(siteUser.getUserId());
		siteUserBuy.setAmount(bidAmount);
		siteUserBuy.setProductId(Integer.parseInt(productId));
		siteUserBuy.setPayType(Constants.PAY_TYPE_1);
		siteUserBuy.setApplyTime(new Date());
		siteUserBuy.setApplyDate(HJBUT.getCurrentDate());
		siteUserBuy.setStatus(Constants.COMMON_STATUS_1);
		siteUserBuy.setTerminalType(getTerminalType(sysOs));
		siteUserBuy.setRate(rate);
		siteUserBuy.setProductType(Constants.PRODUCT_TYPE_2);
		siteUserBuy.setPayType(Constants.PAY_TYPE_4);
		
		int res =siteUserBuyService.insertSiteUserBuy(siteUserBuy);
		if(res != 1){
			log.info("体验标购买失败,保存订单失败"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "购买失败！");
			return resMap;
		}
		
		String logDesc = "体验金投资"+productMap.get("productName");
		int updateCurrentRes = siteUserAccountService.updateExperienceAccount(siteUser.getUserId(), bidAmount, 0, null, null, logDesc);
		if(updateCurrentRes != 1){
			log.info("体验标购买失败,更新体验金账户失败"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "购买失败！");
			return resMap;
		}
		
		//计算收益
		BigDecimal returnAmount = BigDecimal.ZERO;
		String cashReturnDate = HJBUT.currentDate(nextDay, productTime);
		int totalDays = HJBUT.daysBetween(nextDay, cashReturnDate);
		returnAmount = HJBUT.getInterest(bidAmount, rate, totalDays);
		
		//体验金购买成功，新建体验金任务
		SiteUserExperience userExperience = new SiteUserExperience();
		userExperience.setUserId(siteUser.getUserId());
		userExperience.setAmount(bidAmount);
		userExperience.setRate(rate);
		userExperience.setInterestDate(nextDay);
		userExperience.setCashReturnDate(cashReturnDate);
		userExperience.setApplyDate(HJBUT.currentDate());
		userExperience.setOrderNo(orderNo);
		userExperience.setProductId(Integer.parseInt(productId));
		userExperience.setReturnAmount(returnAmount);
		userExperience.setStatus(Constants.COMMON_STATUS_0);
		userExperience.setCreateTime(new Date());
		
		siteUserExperienceMapper.insertSelective(userExperience);
		
		dataMap.put("bidMsg", "恭喜您成功购买体验标"+bidAmountStr+"元");
		dataMap.put("bidDate", HJBUT.currentTime());
		dataMap.put("interestMsg", "预计"+nextDay+"开始计息");
		dataMap.put("incomeMsg", "预计"+cashReturnDate+"收益到账，预计收益"+returnAmount+"元");
		
		resMap.put("data", dataMap);
		return resMap;
	}

	@Override
	public Map<String, Object> myExperienceAccount(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		String type = request.getParameter("type");
		if(StringUtils.isBlank(type)){
			type = "0";
		}
		
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		//查询账户信息
		BigDecimal experienceAccount = BigDecimal.ZERO;
		
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		if(siteUserAccount.getExperienceAccount() != null){
			experienceAccount = siteUserAccount.getExperienceAccount();
		}
		
		//待收收益
		params.put("userId", siteUser.getUserId());
		params.put("status", Constants.COMMON_STATUS_0);
		BigDecimal collectAmount = siteUserExperienceMapper.queryExperienceProfit(params);
		if(collectAmount == null ){
			collectAmount = BigDecimal.ZERO;
		}
		//已收收益
		params.put("status", Constants.COMMON_STATUS_1);
		BigDecimal receivedAmount = siteUserExperienceMapper.queryExperienceProfit(params);
		if(receivedAmount == null ){
			receivedAmount = BigDecimal.ZERO;
		}
		
		SiteUserExperienceExample experienceExample = new SiteUserExperienceExample();
		experienceExample.createCriteria().andUserIdEqualTo(siteUser.getUserId()).andStatusEqualTo(Integer.parseInt(type));
		List<SiteUserExperience> experienceList = siteUserExperienceMapper.selectByExample(experienceExample);
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		for(SiteUserExperience exper:experienceList){
			Map<String,Object> voMap = new HashMap<String, Object>();
			voMap.put("profit", exper.getReturnAmount().setScale(2, BigDecimal.ROUND_DOWN));
			voMap.put("amount", exper.getAmount().setScale(2, BigDecimal.ROUND_DOWN));
			voMap.put("applyDate", exper.getApplyDate());
			voMap.put("cashReturnDate", exper.getCashReturnDate());
			voMap.put("returnDate", exper.getReturnDate());
			dataList.add(voMap);
		}
		
		//体验标
		params = new HashMap<String, Object>();
		params.put("type", "2");
		List<Map<String, Object>> productList = productService.getProductList(params);
		dataMap.put("product", productList.get(0));
		
		dataMap.put("experienceList", dataList);
		dataMap.put("receivedAmount", receivedAmount.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("collectAmount", collectAmount.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("experienceAccount", experienceAccount.setScale(2, BigDecimal.ROUND_DOWN));
		resMap.put("data", dataMap);
		return resMap;
	}

	@Override
	public Map<String, Object> myFixedAccount(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String, Object>();
		//定期列表类型 0：回款中，1：已回款
		String type = request.getParameter("type");
		if(StringUtils.isBlank(type)){
			type = "0";
		}
		
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
		//查询账户
		SiteUserAccount siteUserAccount = new SiteUserAccount();
		siteUserAccount.setUserId(siteUser.getUserId());
		siteUserAccount = siteUserAccountMapper.selectOne(siteUserAccount);
		if(siteUserAccount ==null){
			log.info("未查询到账户数据数据 user_id:"+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "未查询到数据");
			return resMap;
		}
		BigDecimal fixedaccount = siteUserAccount.getFixedAccount();
		BigDecimal fixedExpectIncome = siteUserAccount.getFixedExpectIncome();
		BigDecimal totalFixedIncome = siteUserAccount.getTotalFixedIncome();
		
		//定期明细列表
		params.put("userId", siteUser.getUserId());
		params.put("status", type);
		List<Map<String,Object>> userFixedList = siteUserFixedService.queryUserFixedList(params);
		for(Map<String,Object> voMap : userFixedList){
			String cashReturnDate = String.valueOf(voMap.get("cashReturnDate"));
			int days = HJBUT.daysBetween(HJBUT.currentDate(), cashReturnDate);
			int changeFlag = 0;
			if(days > 3 && Integer.parseInt(String.valueOf(voMap.get("changeFlag")))==0){
				changeFlag = 1;
			}
			String msgTitle = "";
			if(voMap.get("addRate") !=null){
				msgTitle = voMap.get("addRate")+"%加息券";
			}
			if(voMap.get("expectTip") !=null){
				BigDecimal expectTip = new BigDecimal(String.valueOf(voMap.get("expectTip")));
				if(expectTip.compareTo(BigDecimal.ZERO) > 0){
					msgTitle = voMap.get("expectTip")+"元红包";
				}
			}
			BigDecimal amount = new BigDecimal(String.valueOf(voMap.get("amount")));
			voMap.put("amount", amount.setScale(2, BigDecimal.ROUND_DOWN));
			voMap.put("msgTitle", msgTitle);
			voMap.put("changeFlag", changeFlag);
			
		}
		
		//资金回款方式
		List<Map<String,Object>> returnTypeList = commonKeyValueService.queryCommonList(Constants.COMMON_RETURN_TYPE);
		
		dataMap.put("returnTypeList", returnTypeList);
		dataMap.put("fixedList", userFixedList);
		dataMap.put("fixedaccount", fixedaccount.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("fixedExpectIncome", fixedExpectIncome.setScale(2, BigDecimal.ROUND_DOWN));
		dataMap.put("totalFixedIncome", totalFixedIncome.setScale(2, BigDecimal.ROUND_DOWN));
		resMap.put("data", dataMap);
		
		return resMap;
	}

	@Override
	public Map<String, Object> changeFixedReturnType(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		//定期回款方式
		String type = request.getParameter("type");
		String fId = request.getParameter("fid");
//		String tradePwd = request.getParameter("trade_pwd");
//		if(StringUtils.isBlank(type) || StringUtils.isBlank(fId) || StringUtils.isBlank(tradePwd)){
		if(StringUtils.isBlank(type) || StringUtils.isBlank(fId)){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "参数异常");
			return resMap;
		}
		
		SiteUser siteUser = (SiteUser) request.getSession().getAttribute("siteUser");
//		siteUser = new SiteUser();
//		siteUser.setUserId(30010);
		//会话过期
		if (siteUser == null) {
			resMap.put("result_code", MapUtil.INTF_ERR_CODE_416);
			resMap.put("result_info", "会话过期");
			return resMap;
		}
		
//		String tradePwdNew = MD5Utils.encrypt(tradePwd);
//		if(!tradePwdNew.equals(siteUser.getTradePassword())){
//			log.info("交易密码错误  进行申购操作，userId:"+siteUser.getUserId());
//			resMap.put("result_code", MapUtil.INTF_ERR_CODE_418);
//			resMap.put("result_info", "交易密码错误！");
//			return resMap;
//		}
		
		SiteUserFixed userFixed = new SiteUserFixed();
		userFixed.setId(Long.parseLong(fId));
		userFixed.setStatus(Constants.COMMON_STATUS_0);
		userFixed = siteUserFixedMapper.selectOne(userFixed);
		if(userFixed == null){
			log.info("回款方式修改失败:未查询到定期数据:user_id："+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "回款方式修改失败");
			return resMap;
		}
		
		if(userFixed.getChangeFlag() == 1){
			log.info("回款方式修改失败:回款方式已修改过:user_id："+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "回款方式仅支持修改1次");
			return resMap;
		}
		
		SiteUserFixed updateUserFixed = new SiteUserFixed();
		updateUserFixed.setId(Long.parseLong(fId));
		updateUserFixed.setChangeFlag(Constants.COMMON_STATUS_1);
		updateUserFixed.setReturnType(type);
		updateUserFixed.setUpdateTime(new Date());
		int res = siteUserFixedMapper.updateByPrimaryKeySelective(updateUserFixed);
		if(res != 1){
			log.info("回款方式修改失败:user_id："+siteUser.getUserId());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "回款方式修改失败");
			return resMap;
		}
		
		resMap.put("data", dataMap);
		
		return resMap;
	}

	@Override
	public Map<String, Object> queryFixedAgreement(HttpServletRequest request) {
		Map<String,Object> resMap =MapUtil.getRetMap();
		Map<String,Object> dataMap = new HashMap<String, Object>();
		
		String fId = request.getParameter("fid");
		if(StringUtils.isBlank(fId)){
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "参数异常");
			return resMap;
		}
		
		SiteUserFixed userFixed = new SiteUserFixed();
		userFixed.setId(Long.parseLong(fId));
		userFixed = siteUserFixedMapper.selectOne(userFixed);
		if(userFixed == null){
			log.info("定期协议查询定期订单失败:f_id："+fId);
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "数据异常");
			return resMap;
		}
		
		SiteUser siteUser = new SiteUser();
		siteUser.setUserId(userFixed.getUserId());
		siteUser = siteUserMapper.selectOne(siteUser);
		if(siteUser == null){
			log.info("定期协议查询定期用户信息失败:user_id："+userFixed.getUserId()+",order_no:"+userFixed.getOrderNo());
			resMap.put("result_code", MapUtil.INTF_ERR_CODE);
			resMap.put("result_info", "数据异常");
			return resMap;
		}
		
//		dataMap.put("realName", siteUser.getRealName());
//		dataMap.put("mobile", siteUser.getMobilePhone());
		dataMap.put("orderNo", "HJS"+userFixed.getOrderNo());
		dataMap.put("cardNumber", siteUser.getCardNumber());
		resMap.put("data", dataMap);
		return resMap;
	}

	@Override
	public List<Product> selectByExample(ProductExample example) {
		return productMapper.selectByExample(example);
	}
	
}
